package com.chen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.blog.common.api.CommonResult;
import com.chen.blog.mapper.FollowMapper;
import com.chen.blog.mapper.UserMapper;
import com.chen.blog.model.Follow;
import com.chen.blog.model.User;
import com.chen.blog.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chen
 * @since 2022-01-24
 */
@Service
@Transactional
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取热门作者功能实现
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getHotAuthor() {
        return followMapper.getHotAuthor();
    }

    /**
     * 获取指定id用户的关注列表功能实现
     *
     * @param currentPage
     * @param pageSize
     * @param user
     * @return
     */
    @Override
    public CommonResult getByPage(Integer currentPage, Integer pageSize, User user) {
        List<Integer> authorIds = followMapper.selectList(new QueryWrapper<Follow>().select("author_id").eq("user_id", user.getId())).stream()
                .map(Follow::getAuthorId).collect(Collectors.toList());
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        //过滤用户密码
        wrapper.select(User.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("password"));
        wrapper.in(User::getId, authorIds);
        wrapper.like(!StringUtils.isEmpty(user.getUsername()), User::getUsername, user.getUsername());
        Page<User> page = userMapper.selectPage(new Page<>(currentPage, pageSize), wrapper);
        if (currentPage > page.getPages()) {
            return CommonResult.success(null, userMapper.selectPage(new Page<>(page.getPages(), pageSize), wrapper));
        }
        return CommonResult.success(null, userMapper.selectPage(new Page<>(currentPage, pageSize), wrapper));
    }
}
